package com.company.oa.meeting.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.company.oa.meeting.dto.MeetingMinutesDTO;
import com.company.oa.meeting.entity.Meeting;
import com.company.oa.meeting.entity.MeetingMinutes;
import com.company.oa.meeting.mapper.MeetingMapper;
import com.company.oa.meeting.mapper.MeetingMinutesMapper;
import com.company.oa.meeting.service.MeetingMinutesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * 会议纪要服务实现类
 */
@Service
public class MeetingMinutesServiceImpl extends ServiceImpl<MeetingMinutesMapper, MeetingMinutes> implements MeetingMinutesService {

    @Autowired
    private MeetingMapper meetingMapper;

    @Override
    @Transactional
    public boolean saveMinutes(MeetingMinutesDTO minutesDTO, Long creatorId, String creatorName) {
        // 检查会议是否存在
        Meeting meeting = meetingMapper.selectById(minutesDTO.getMeetingId());
        if (meeting == null) {
            throw new RuntimeException("会议不存在");
        }
        
        // 检查是否已有纪要
        MeetingMinutes existingMinutes = getByMeetingId(minutesDTO.getMeetingId());
        
        if (existingMinutes != null) {
            // 更新纪要
            existingMinutes.setContent(minutesDTO.getContent());
            existingMinutes.setUpdateTime(LocalDateTime.now());
            
            return updateById(existingMinutes);
        } else {
            // 创建新纪要
            MeetingMinutes minutes = new MeetingMinutes();
            minutes.setMeetingId(minutesDTO.getMeetingId());
            minutes.setContent(minutesDTO.getContent());
            minutes.setCreatorId(creatorId);
            minutes.setCreatorName(creatorName);
            minutes.setCreateTime(LocalDateTime.now());
            minutes.setIsDeleted(0);
            
            return save(minutes);
        }
    }

    @Override
    public MeetingMinutes getByMeetingId(Long meetingId) {
        LambdaQueryWrapper<MeetingMinutes> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MeetingMinutes::getMeetingId, meetingId)
               .eq(MeetingMinutes::getIsDeleted, 0);
        
        return getOne(wrapper);
    }

    @Override
    @Transactional
    public boolean deleteMinutes(Long id) {
        MeetingMinutes minutes = getById(id);
        if (minutes == null) {
            throw new RuntimeException("会议纪要不存在");
        }
        
        minutes.setIsDeleted(1);
        minutes.setUpdateTime(LocalDateTime.now());
        
        return updateById(minutes);
    }
} 